package com.pb.infra.oth.handler;

import com.pb.infra.oth.entity.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应处理类
 */
@RestControllerAdvice(basePackages = "com.pb")
public class RestResponseHandler implements ResponseBodyAdvice<Object> {

    @Value("${spring.application.name:agnes}")
    private String serviceName;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.getParameterType().equals(Void.TYPE);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContenType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        Result result;
        if (body instanceof Result) {
            result = (Result) body;
        } else if (body instanceof String){
            return (String) body;
        }
         else {
            result = Result.ok(body);
        }
        if (null == result.getService()) {
            result.setService(this.serviceName);
        }
        return result;
    }

}
